package com.fulihui.systemcore.repository.impl;

import com.fulihui.systemcore.dal.convertor.MenuConv;
import com.fulihui.systemcore.dal.dataobj.Menu;
import com.fulihui.systemcore.dal.mapper.MenuMapper;
import com.fulihui.systemcore.dto.MenuDTO;
import com.fulihui.systemcore.repository.MenuRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author leeson 2016年5月17日 下午2:16:35
 *
 */
@Repository
public class MenuRepositoryImpl implements MenuRepository {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<MenuDTO> queryTopMenu(boolean isContainsChild, String projectCode) {
        List<Menu> menuList = menuMapper.queryTopMenu(projectCode);

        List<MenuDTO> menuDTOList = MenuConv.convert2List(menuList);
        if (isContainsChild) {
            for (MenuDTO menuDTO : menuDTOList) {
                menuDTO.setChildMenuList(
                    MenuConv.convert2List(menuMapper.queryByParentCode(menuDTO.getCode())));
            }
        }

        return menuDTOList;
    }

    @Override
    public List<MenuDTO> queryChildMenu(String menuCode) {
        return MenuConv.convert2List(menuMapper.queryByParentCode(menuCode));
    }

    @Transactional
    @Override
    public void batchUpdateIndex(Map<Integer, Integer> idAndIndexMap) {
        idAndIndexMap.forEach(menuMapper::updateIndexById);
    }

    @Override
    public void insert(MenuDTO record) {
        menuMapper.insert(MenuConv.convert2DO(record));
    }

    @Override
    public void update(MenuDTO record) {
        menuMapper.update(MenuConv.convert2DO(record));
    }

    @Override
    public MenuDTO queryById(int menuId) {
        return MenuConv.convert2DTO(menuMapper.queryById(menuId));
    }

    @Transactional
    @Override
    public void delete(int menuId) {
        Menu menu = menuMapper.queryById(menuId);
        if (StringUtils.isEmpty(menu.getParentCode())) {
            List<Menu> menuList = menuMapper.queryByParentCode(menu.getCode());
            if (null != menuList && menuList.size() > 0) {
                for (Menu m : menuList) {
                    menuMapper.delete(m.getId());
                }
            }
        }
        menuMapper.delete(menuId);
    }

    @Override
    public MenuDTO queryByCode(String code) {
        return MenuConv.convert2DTO(menuMapper.queryByCode(code));
    }

    @Override
    public int maxIndex(String projectCode, String parentCode) {
        return menuMapper.maxIndex(projectCode, parentCode);
    }
}